package com.metamech.vorpal.handler;
import org.apache.log4j.Logger;

import com.metamech.jabber.ErrorTool;
import com.metamech.jabber.Session;
import com.metamech.jabber.xml.Packet;
import com.metamech.jabber.xml.PacketListener;
import com.metamech.log.Log;
import com.metamech.vorpal.GroupChatManager;
import com.metamech.vorpal.User;
import com.metamech.vorpal.UserIndex;

/**
 * Title:
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author
 * @version 1.0
 */

public class PresenceHandler implements PacketListener {
	private static Logger logger=Logger.getLogger(PresenceHandler.class);
	UserIndex userIndex;
	GroupChatManager chatMan = GroupChatManager.getManager();
	public PresenceHandler(UserIndex index) { userIndex = index; }

	public void notify(Packet packet){
		if (packet.getSession().getStatus() != Session.AUTHENTICATED){
			logger.info("PresenceHandler: Not authenticated" + packet.toString());
			packet.setTo(null);
			packet.setFrom(null);
			ErrorTool.setError(packet,401,"You must be authenticated to send presence");
			MessageHandler.deliverPacket(packet);
	    } else if (chatMan.isChatPacket(packet)){
	    	logger.info("PresenceHandler: groupchat presence");
	    	chatMan.handleChatPresence(packet);
	    } else {
	    	logger.info("PresenceHandler: user presence sending to user roster: " + packet.getSession().getJID().getUser());
	    	User user = userIndex.getUser(packet.getSession().getJID().getUser());
	    	user.getRoster().updatePresence(packet);
	    }
	}
  // Session index is not used yet...  Had to keep it here to keep in sync
  // with the book code.
	/*SessionIndex sessionIndex;
  	GroupChatManager chatMan = GroupChatManager.getManager();
  	public PresenceHandler(SessionIndex index) { 
  		sessionIndex = index; 
  	}

  	public void notify(Packet packet){
  		if (chatMan.isChatPacket(packet)){
  			Log.trace("PresenceHandler: groupchat presence");
  			chatMan.handleChatPresence(packet);
  		} else {
  			Log.trace("PresenceHandler: delivering presence packet " + packet.toString());
  			MessageHandler.deliverPacket(packet);
  		}
  	}*/
}